package com.sgb.kjwl.view.ui.activity.manage;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebsiteUpdataMyjjBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.widget.SelectAlbumPopWindow;
import com.sgb.link.view.widget.OneAndTwoLevelMultipleChoiceWindow;
import com.sgb.kjwl.viewmodel.manage.WebsiteUpdataMyXiXinModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.inject.Inject;

/**
 * @author 张驰
 * @date 2021/6/4 10:29
 * @Description
 * @name com.sgb.kjwl.view.ui.activity.manage
 */
public class WebsiteUpDataMyXiXinActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    @Inject
    WebsiteUpdataMyXiXinModel viewModel;
    private ActivityWebsiteUpdataMyjjBinding binding;
    private WebsiteInfoEntity websiteMyInfoEntity;
    private RequestManager requestManager;
    //相册选择弹窗
    SelectAlbumPopWindow selectAlbumPopWindow;

    //经营类型
    private List<PickFilterEntity<List<PickFilterEntity>>> manageTypeList = new ArrayList<>();


    private OneAndTwoLevelMultipleChoiceWindow window;

    private List<PickFilterEntity> comReallyTypes = new ArrayList<>();

    public static void start(Activity myActivity, WebsiteInfoEntity websiteInfoEntity, int request_code) {
        Intent intent = new Intent(myActivity, WebsiteUpDataMyXiXinActivity.class);
        intent.putExtra("Data", websiteInfoEntity);
        myActivity.startActivityForResult(intent, request_code);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).
                enterpriseManageModule(new EnterpriseManageModule(this)).
                build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_website_updata_myjj);
        binding.include.titleView.setText("基本信息");
        requestManager = Glide.with(this);
        binding.llMyImageView.setOnClickListener(this);
        binding.llAddressView.setOnClickListener(this);
        binding.tvUpdate.setOnClickListener(this);
        binding.tvUpdate.setOnClickListener(this);
        binding.iiTvPhone.setInputType(8194);//输入数字
        binding.iiTvPhone.setInfilterType(ItemInputTextView.TYPE_NUM);//输入数字
        //binding.tvItvName.setInfilterType(ItemInputTextView.TYPE_DEFAULT);
        binding.tvItvCompany.setInfilterType(ItemInputTextView.TYPE_DEFAULT);
        binding.tvItvPosition.setInfilterType(ItemInputTextView.TYPE_DEFAULT);
        binding.tvItvNation.setInfilterType(ItemInputTextView.TYPE_NAME);
        binding.tvItvNative.setInfilterType(ItemInputTextView.TYPE_NAME);
        binding.tvBirthday.setOnWholeItemClickListener(this);
        binding.include.ivBack.setOnClickListener(this);
        binding.manageType.setOnClickListener(this);
        binding.tvItvName.setContent(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, ""));
        binding.etSign.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String inputText = binding.etSign.getText().toString();
                String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
                String patterStr = stringFilter(inputText, regEx);
                if (!inputText.equals(patterStr)) {
                    binding.etSign.setText(patterStr);
                    binding.etSign.setSelection(patterStr.length());//设置新的光标所在位置
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        binding.tvItvEmail.content_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String inputText = binding.tvItvEmail.content_edt.getText().toString();
                String regEx = "[^a-zA-Z0-9\\.@]";
                String patterStr = stringFilter(inputText, regEx);
                if (!inputText.equals(patterStr)) {
                    binding.tvItvEmail.content_edt.setText(patterStr);
                    binding.tvItvEmail.content_edt.setSelection(patterStr.length());//设置新的光标所在位置
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        viewModel.getWebsiteInfoData().observe(this, myEntity -> {
            if (myEntity == null) {
                MToast.showToast(this, "操作成功");
                websiteMyInfoEntity.setMainBusiness(binding.comServiceTypeDetail.getEditContent());
                Intent intent = new Intent();
                intent.putExtra("Data", websiteMyInfoEntity);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                websiteMyInfoEntity = myEntity;
                if (!TextUtils.isEmpty(websiteMyInfoEntity.getMainBusiness())){
                    binding.comServiceTypeDetail.getEditText().setText(websiteMyInfoEntity.getMainBusiness());
                }
//                if (!TextUtils.isEmpty(websiteMyInfoEntity.getNewMainBusinessName())){
//                    binding.huixian.setVisibility(View.VISIBLE);
//                    binding.huixian.setText(websiteMyInfoEntity.getNewMainBusinessName());
//                }
                if (!TextUtils.isEmpty(websiteMyInfoEntity.getMainOtherBusiness())){
                    binding.huixian.setVisibility(View.VISIBLE);
                    binding.huixian.setText(websiteMyInfoEntity.getMainOtherBusiness());
                }
                binding.setViewModel(websiteMyInfoEntity);
//                if (!TextUtils.isEmpty(websiteMyInfoEntity.getServiceTypeName()) && !TextUtils.isEmpty(websiteMyInfoEntity.getServiceType())){
//                    String[] serviceTypeNames = websiteMyInfoEntity.getServiceTypeName().split(",");
//                    String[] serviceTypes = websiteMyInfoEntity.getServiceType().split(",");
//                    if (serviceTypeNames.length == serviceTypes.length){
//                        PickFilterEntity entity;
//                        comReallyTypes.clear();
//                        for (int i = 0; i < serviceTypeNames.length; i++) {
//                            entity = new PickFilterEntity();
//                            entity.setName(serviceTypeNames[i]);
//                            entity.setNo(serviceTypes[i]);
//                            comReallyTypes.add(entity);
//                        }
//
//                    }
//                }
            }
        });
        viewModel.getMessage().observe(this
                , s -> {
                    websiteMyInfoEntity.setLogo(s);
                    setAvatarView(s);
                });
        viewModel.businessType.observe(this, new Observer<List<PickFilterEntity<List<PickFilterEntity>>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<List<PickFilterEntity>>> pickFilterEntities) {
                if (pickFilterEntities != null) {
                    manageTypeList.clear();
                    manageTypeList.addAll(pickFilterEntities);
                    showManageTypePop();
                }
            }
        });
        binding.cbNan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                binding.cbNan.setChecked(isChecked);
                binding.cbNv.setChecked(!isChecked);
                websiteMyInfoEntity.setSex(WebsiteInfoEntity.USER_GENDER_MAN);
            }
        });
        binding.cbNv.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                binding.cbNan.setChecked(!isChecked);
                binding.cbNv.setChecked(isChecked);
                websiteMyInfoEntity.setSex(WebsiteInfoEntity.USER_GENDER_WOMEN);
            }
        });
    }

    private String stringFilter(String str, String regEx) throws PatternSyntaxException {
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 显示用户图像
     *
     * @param logo
     */
    private void setAvatarView(String logo) {
        if (!TextUtils.isEmpty(logo)) {
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.image_website_dfg)//图片加载出来前，显示的图片
                    .error(R.mipmap.image_website_dfg)//图片加载失败后，显示的图片
                    .transform(new CircleCrop());
            requestManager.load(logo).apply(options).into(binding.ivShopAvatar);
        }
    }

    @Override
    protected void init() {
        if (getIntent().getSerializableExtra("Data") != null) {
            websiteMyInfoEntity = (WebsiteInfoEntity) getIntent().getSerializableExtra("Data");
            setAvatarView(websiteMyInfoEntity.getLogo());
            viewModel.getWebsiteInfoData().postValue(websiteMyInfoEntity);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_address_view:
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "联系地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                if (!TextUtils.isEmpty(websiteMyInfoEntity.getLatitude())) {
                    intent.putExtra(SelectAddressActivity.LATITUDE, Double.valueOf(Objects.requireNonNull(websiteMyInfoEntity).getLatitude()));
                    intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.valueOf(Objects.requireNonNull(websiteMyInfoEntity).getLongitude()));
                } else {
                    intent.putExtra(SelectAddressActivity.LATITUDE, 34.20843);
                    intent.putExtra(SelectAddressActivity.LONGTITUDE, 108.91962);
                }
                startActivityForResult(intent, 255);
                break;
            case R.id.ll_my_image_view:
                initAlbumPop();
                break;
            case R.id.tv_update:
                if (!ClickUtils.isDoubleClick()) {
                    Map<String, Object> map = saveOrUpData();
                    if (map == null) return;
                    viewModel.saveOrUpdate(getActivity(), map);
                }
                break;
            case R.id.manage_type:
                if (!manageTypeList.isEmpty()) {
                    showManageTypePop();
                } else {
                    viewModel.getBusinessType();
                }
                break;
        }
    }

    private void showManageTypePop() {
        if (manageTypeList.isEmpty()) return;
        if (window == null) {
            window = new OneAndTwoLevelMultipleChoiceWindow(this);
        }
        window.setTitle("经营类型");
        window.setBgView(binding.grayLayout);
        window.setOnResultClick(list1 -> {
            if (list1.size() > 20){
                MToast.showToast(this, "最多选择20个");
                return;
            }
            StringBuilder builderName = new StringBuilder();
            StringBuilder builderCode= new StringBuilder();
            for (PickFilterEntity entity : list1) {
                builderName.append(entity.getName()).append(",");
                builderCode.append(entity.getId()).append(",");
            }
            comReallyTypes.clear();
            comReallyTypes.addAll(list1);
            binding.manageType.setText(builderName.substring(0, builderName.length() - 1));
            viewModel.getWebsiteInfoData().getValue().setServiceTypeName(builderName.substring(0, builderName.length() - 1));
            viewModel.getWebsiteInfoData().getValue().setServiceType(builderCode.substring(0, builderCode.length() - 1));
        });
        window.setHistory(manageTypeList, comReallyTypes);
        window.showPopwindow(binding.manageType, Gravity.BOTTOM, 0, 0);
    }

    private Map<String, Object> saveOrUpData() {
        Map<String, Object> map = new HashMap<>();
        map.put("logo", viewModel.getWebsiteInfoData().getValue().getLogo());//头像

        if (!TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getRealName())) {
            map.put("realName", viewModel.getWebsiteInfoData().getValue().getRealName());//姓名
        }

//        if (TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getSex())) {
//            MToast.showToast(getActivity(), "请选择性别，后再保存");
//            return null;
//        }
        map.put("sex", viewModel.getWebsiteInfoData().getValue().getSex());//性别

        if (TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getBirthday())) {
            MToast.showToast(getActivity(), "请选择出生日期");
            return null;
        }
        map.put("birthday", viewModel.getWebsiteInfoData().getValue().getBirthday());//出生日期
        if (!TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getTelephone())) { //联系电话
            if (!CheckUtils.isMobileNum(viewModel.getWebsiteInfoData().getValue().getTelephone())) { //联系电话
                MToast.showToast(getActivity(), "请输入正确电话号码");
                return null;
            }
            map.put("telephone", viewModel.getWebsiteInfoData().getValue().getTelephone());//联系电话
        }

        if (!TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getEmail())) { //邮箱
            if (!CheckUtils.isEmails(viewModel.getWebsiteInfoData().getValue().getEmail())){
                MToast.showToast(getActivity(), "请输入正确邮箱账号");
                return null;
            }
        }
        map.put("email", viewModel.getWebsiteInfoData().getValue().getEmail());//邮箱

        map.put("position", viewModel.getWebsiteInfoData().getValue().getPosition());//职位

        map.put("companyName", viewModel.getWebsiteInfoData().getValue().getCompanyName());//所受企业

//        if (!TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getProvinceNo())) { //联系地址
//            map.put("provinceId", viewModel.getWebsiteInfoData().getValue().getProvinceNo());//联系地址
//            map.put("provinceName", viewModel.getWebsiteInfoData().getValue().getProvinceName());//联系地址
//        }
//
//        if (!TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getCityId())) { //联系地址
//            map.put("cityId", viewModel.getWebsiteInfoData().getValue().getCityId());//联系地址
//            map.put("cityName", viewModel.getWebsiteInfoData().getValue().getCityName());//联系地址
//        }

//        if (!TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getDistrictNo())) { //联系地址
//            map.put("districtNo", viewModel.getWebsiteInfoData().getValue().getDistrictNo());//联系地址
//            map.put("districtName", viewModel.getWebsiteInfoData().getValue().getDistrictName());//联系地址
//        }
//        if (TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getServiceType())) { //经营业务
//            MToast.showToast(getActivity(), "请选择经营类型");
//            return null;
//        }

        map.put("latitude", viewModel.getWebsiteInfoData().getValue().getLatitude());//联系地址
        map.put("longitude", viewModel.getWebsiteInfoData().getValue().getLongitude());//联系地址
        map.put("nation", viewModel.getWebsiteInfoData().getValue().getNation());//民族
        map.put("nativePlace", viewModel.getWebsiteInfoData().getValue().getNativePlace());//籍贯

        map.put("detailAddress", viewModel.getWebsiteInfoData().getValue().getDetailAddress());//联系地址
        map.put("mapAddress", viewModel.getWebsiteInfoData().getValue().getMapAddress());//联系地址
        map.put("serviceType", viewModel.getWebsiteInfoData().getValue().getServiceType());//经营业务
        map.put("serviceTypeName", viewModel.getWebsiteInfoData().getValue().getServiceTypeName());
        map.put("mainBusiness", binding.comServiceTypeDetail.getEditContent());
        map.put("personalSignature", viewModel.getWebsiteInfoData().getValue().getPersonalSignature());//个性签名

        map.put("siteType", "0");//网站类型  0-个人 1-企业 2-团队

        if (!TextUtils.isEmpty(viewModel.getWebsiteInfoData().getValue().getPersonId())) { //用户id
            map.put("id", viewModel.getWebsiteInfoData().getValue().getPersonId());
        }
        return map;
    }


    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.tv_birthday:
                showCourseTimePop();
                break;
        }
    }

    //时间选择
    private void showCourseTimePop() {
//        Calendar dayCalendar = Calendar.getInstance();
//        dayCalendar.setTime(new Date());
//        dayCalendar.add(Calendar.DAY_OF_MONTH, 1);

        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                viewModel.getWebsiteInfoData().getValue().setBirthday(date.getTime() + "");
                viewModel.getWebsiteInfoData().postValue(viewModel.getWebsiteInfoData().getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择出生日期")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
//                .setRangDate(dayCalendar, null)
                .build();
        timePicker.show();
    }


    /**
     * 弹出相册选择
     */
    private void initAlbumPop() {
        if (selectAlbumPopWindow == null) {
            //满足条件，创建SelectAlbumPopWindow
            selectAlbumPopWindow = new SelectAlbumPopWindow(this);
        }
        //设置背景
        selectAlbumPopWindow.setBgView(binding.grayLayout);
        //设置点击回调
        selectAlbumPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int type = (int) key1;
                if (type == 0) {
                    pictureSelector(true, 500, 1);
                    selectAlbumPopWindow.dismiss();
                }
            }
        });
        selectAlbumPopWindow.showDownPopwindow(binding.grayLayout,true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case 255://地图地址选择回调
                if (data == null)
                    return;
                setAddressText(data);
                break;
        }
    }

    /*
     * 请求地图地址返回的数据
     * */
    private void setAddressText(Intent data) {
        double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
        double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
        String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
        websiteMyInfoEntity.setLatitude(lat + "");
        websiteMyInfoEntity.setLongitude(lon + "");
        websiteMyInfoEntity.setDetailAddress(address);
        websiteMyInfoEntity.setMapAddress(address);
        viewModel.getWebsiteInfoData().postValue(websiteMyInfoEntity);
    }

    /**
     * 图片选择之后返回图片本地资源文件地址
     *
     * @param selectList
     */
    @Override
    protected void onPictureSelectorResult(List<LocalMedia> selectList) {
        // 获取到图片的本地路径
        String path = selectList.get(0).getCompressPath();
        //保存在文件中
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            //接口上传文件
            viewModel.uploadAvatar(getActivity(), file);
            //上传时，出现上传弹窗
            DialogHelper.showProgressDialog(this, null, "头像上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        } else {
            MToast.showToast(getApplicationContext(), "获取图片失败！");
        }
    }
}
